<template>
  <div class="main-container container-fluid container-limited page-holder">
    <groups-breadcrumb />
    <div class="border-bottom p-x-16">
      <announcement-item
        v-for="item in announcements"
        :key="item.id"
        :item="item"
        @deleted="deleted"
        @check="checkItem"
      />
      <load-more :list="announcements" :next-page="nextPage" :loading="loading" />
    </div>
    <announcement-release v-if="isWebAdmin || isGroupOwner || isGroupAdmin" @released="released" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import GroupsBreadcrumb from '@/views/groups/components/breadcrumb';
import LoadMore from '@/components/load-more';
import { formatAnnouncement, formatAnnouncements } from '@/views/groups/format';
import AnnouncementItem from './components/announcement-item';
import AnnouncementRelease from './components/announcement-release';

export default {
  name: 'GroupsNotice', // 群组公告
  components: {
    GroupsBreadcrumb,
    LoadMore,
    AnnouncementItem,
    AnnouncementRelease,
  },
  data() {
    return {
      announcements: [],
      nextPage: null,
      loading: false,
    };
  },
  computed: {
    ...mapGetters(['isWebAdmin', 'isGroupOwner', 'isGroupAdmin']),
    groupId() { return this.$route.params.groupId; },
  },
  created() { this.loadAnnouncements(); },
  methods: {
    loadAnnouncements() {
      this.loading = true;
      this.$api.groupAnnouncements.index({
        groupId: this.groupId,
      }).then((res) => {
        this.announcements = this.announcements.concat(formatAnnouncements(res.data));
        this.nextPage = res.kaminari.next_page;
      }).catch(() => {})
        .then(() => { this.loading = false; });
    },
    // 发布了公告
    released(item) { this.announcements.unshift(formatAnnouncement(item)); },
    // 删除了公告
    deleted(item) {
      const index = this.announcements.indexOf(item);
      this.announcements.splice(index, 1);
    },
    // 检查公告（点击查看评论后会请求一次show接口，确保评论数量正确）
    checkItem(item, id) {
      const index = this.announcements.map(i => i.id).indexOf(id);
      if (item) this.announcements.splice(index, 1, formatAnnouncement(item));
      else this.announcements.splice(index, 1, { id, deleted: true });
    },
  },
  watch: {
    groupId() { this.loadAnnouncements(); },
  },
};
</script>

<style></style>
